// pages/mall/orderConfirm/orderConfirm.js
import * as API_Mall_Confirm from '../../../api/mall/mallConfirm'
import * as Api_Mall_Address from '../../../api/mall/address'
import * as API_Mall_coupons from '../../../api/mall/coupons'
import * as API_Mall_Order from '../../../api/mall/order'


Page({

  /**
   * 页面的初始数据
   */
  data: {
    allGoods:[],
    goodsCount:0,
    couponIndex:0,
    couponsList:[],
    lastPrice:0,
    productTotalPrice:'',
    addr:{},
    addrStr:'',
    addrId:'',
    goodsList:[],
    addrFlag:false,
    couponId:0,
    cmParams:{
      primaryKey:'',
      specsId:''
    },
    remark:'',
    payState:false
  },
  changeRemark(e){
    this.setData({remark:e.detail.value})
  },
  submmitOrder(){
    this.setData({payState:true});
    if(!this.data.addrStr){
      wx.showToast({
        title: '请填写地址',
        icon:'none',
        duration:1500
      })
      this.setData({payState:false});
      return
    }
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];  //上一个页面
    let path = prevPage.route.split("/")
    let that = this
    let param = {
      cartVos:that.data.allGoods,
      couponId:that.data.couponId,
      route:path[path.length-1],
      customerRemark:that.data.remark,
      addrId:that.data.addr.id
    }
    API_Mall_Order.create(param).then(res=>{
      that.setData({
          saleState:true
        })
        if(res.code==200){
         let orderId= res.data.id;
          that.toPay(orderId);
        }else{
          wx.showToast({
            title: res.msg
          })
       
          that.setData({payState:false});
        }
    })
  },
  toPage(){
    getApp().globalData.toIndex = true
    wx.switchTab({
      url: '/pages/UCenter/index/index',
    })
  },
  toPay:function(orderId){
    let that=this;
    let params={orderId:orderId};
    API_Mall_Order.delayPay(params).then(res=>{
      if(res.code==200){

        let payment=res.data;
      if(payment.status=="succeeded"){
        let expend=payment.expend;
        let pay_info=JSON.parse(expend.pay_info);

        wx.requestPayment(
          {
              'timeStamp':pay_info.timeStamp,
              'nonceStr': pay_info.nonceStr,
              'package': pay_info.package,
              'signType': pay_info.signType,
              'paySign': pay_info.paySign,
              'success':function(res){
                wx.showToast({
                  title: '支付成功',
                })
                setTimeout(()=>{
                    that.toPage()
                }, 1500)

                },
                'fail':function(res){
                  
                },
                'complete':function(res){

                }
          })
      }
      }else{
        that.setData({payState:false});
        wx.showToast({
          title: res.msg
        })
      }

    })

  },
  goAddrList(){
    wx.navigateTo({
      url: '../../mall/receAddressList/receAddressList',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.addrId){
      this.loadAddr(options.addrId)
    }else{
      Api_Mall_Address.getDefault().then(res=>{
        if(res){
          this.loadAddr(res.id)
        }
      })
    }
    let arr = JSON.parse(options.params)
    this.setData({
      allGoods:arr
    })
    // var ids = arr.map(item => item.specsId)
    this.confirm(arr)
  },
  confirm(e){
    API_Mall_Confirm.confirm(e).then(res=>{
      let arr = []
      for(var i = 0; i<res.data.length;i++){
        let item = res.data[i]
        for(var key in item){
          arr.push(item[key])
        }
      }
      this.setData({
        goodsList:arr
      })
    this.loadCoupons(e)
    })
  },
  loadCoupons(e){
    API_Mall_coupons.getCanUseList(e).then(res=>{
      if(res.data.length>0){
        this.setData({
          couponsList:res.data,
          couponId:res.data[0].id 
        })
      }
      this.loadTotalPrice()
    })
  },
  loadTotalPrice(){
    let arr = this.data.goodsList.map((v,i)=>{
      return v.price*v.count;
    })
    let countArr = this.data.goodsList.map((v,i)=>{
      return v.count;
    })
    var goodsCount = countArr.reduce((pre,cur)=>pre+cur)
    var total=arr.reduce((prev,curr)=>prev+curr)
    this.setData({
      productTotalPrice:total,
      lastPrice:total,
      goodsCount:goodsCount
    })
    this.loadLastPrice()
  },
  loadLastPrice(){
    if(!this.data.couponsList.length>0){
      return
    }
    let coupon = this.data.couponsList[this.data.couponIndex]
    let price = this.data.productTotalPrice
    let last = ((price * 100)-(coupon.money * 100) )/ 100
    if(last<=0){
      this.setData({
        lastPrice:0.01
      })
    }else{
      this.setData({
        lastPrice:last
      })
    }
   
  },
  bindPickerChange(e){
    let that = this
    this.setData({
      couponIndex:e.detail.value,
      couponId:that.data.couponsList[e.detail.value].id
    })
    this.loadLastPrice()
  },
  loadAddr(e){
    Api_Mall_Address.getOne(e).then(res=>{ 
      this.setData({
        addr:res,
        addrFlag:true,
        addrStr:res.areaName
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})